package com.stylefeng.guns.modular.apple.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.SftpException;
import com.stylefeng.guns.core.common.exception.BizExceptionEnum;
import com.stylefeng.guns.core.exception.GunsException;
import com.stylefeng.guns.modular.apple.properties.SftpProperties;
import com.stylefeng.guns.modular.upload.FileInfo;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.io.SAXReader;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.zip.ZipFile;

import org.json.JSONObject;
import org.json.JSONException;

/**
 * 使用Sftp上传文件工具类
 **/
@Slf4j
public class FileUtil {
    /**
     * 读取xml文件信息到map
     * */
    HashMap<String, String> fetchInfoFromXmlFile(String filePath) {
        SAXReader reader = new SAXReader();
        return new HashMap<>();
    }


    /**
     * 调用sftp上传文件
     * 使用UUID作为文件唯一名称
     * @param file
     * @param sftpInfo sftp信息对象
     * @return
     */
    public static String uploadFile(MultipartFile file, SftpProperties sftpInfo){

        log.info("开始上传 >>>>>>>>");
        SftpUtil sftpUtil = null;
        String remoteFile = "";
        String uuid = UUID.randomUUID().toString().replaceAll("-","");
        remoteFile = sftpInfo.getBasePath() + uuid + SftpUtil.getExtName(file.getOriginalFilename());
        try {
            sftpUtil = new SftpUtil(sftpInfo);
            sftpUtil.uploadFile(remoteFile,file.getInputStream());
        } catch (JSchException e) {
            log.error("上传出错， JSchException： {}",e.getMessage());
            e.printStackTrace();
            throw new GunsException(BizExceptionEnum.APPLE_SFTP_UPLOAD_ERROR);
        } catch (SftpException | IOException e) {
            log.error("上传出错， SftpException | IOException： {}",e.getMessage());
            e.printStackTrace();
            e.printStackTrace();
            throw new GunsException(BizExceptionEnum.APPLE_SFTP_UPLOAD_ERROR);
        } finally {
            if (sftpUtil != null){
                sftpUtil.close();
            }
        }

        log.info("上传完成 <<<<<<<<<<");
        return  remoteFile;
    }

    /**
     * 调用sftp上传文件
     * 使用自定义文件名称
     * @param file 文件对象
     * @param fileName 文件名称
     * @param sftpInfo sftp信息对象
     * @return
     */
    public static String uploadFile(MultipartFile file, String fileName,SftpProperties sftpInfo){
//        log.info("开始上传 >>>>>>>>");
//        SftpUtil sftpUtil = null;
        String remoteFile = "";
        remoteFile = sftpInfo.getBasePath() + fileName;

//        try {
//            sftpUtil = new SftpUtil(sftpInfo);
//            sftpUtil.uploadFile(remoteFile,file.getInputStream());
//        } catch (JSchException e) {
//            log.error("上传出错， JSchException： {}",e.getMessage());
//            e.printStackTrace();
//            throw new GunsException(BizExceptionEnum.APPLE_SFTP_UPLOAD_ERROR);
//        } catch (SftpException | IOException e) {
//            log.error("上传出错， SftpException | IOException： {}",e.getMessage());
//            e.printStackTrace();
//            throw new GunsException(BizExceptionEnum.APPLE_SFTP_UPLOAD_ERROR);
//        } finally {
//            if (sftpUtil != null){
//                sftpUtil.close();
//            }
//        }
//
//        log.info("上传完成 <<<<<<<<<<");
        LocalFileUtils.uploadFile(file, FileInfo.builder()
                .tmpPath(sftpInfo.getBasePath()).fileName(fileName)
                .build());
//        try {
//            sftpUtil = new SftpUtil(sftpInfo);
//            sftpUtil.uploadFile(remoteFile,file.getInputStream());
//        } catch (JSchException e) {
//            log.error("上传出错， JSchException： {}",e.getMessage());
//            e.printStackTrace();
//            throw new GunsException(BizExceptionEnum.APPLE_SFTP_UPLOAD_ERROR);
//        } catch (SftpException | IOException e) {
//            log.error("上传出错， SftpException | IOException： {}",e.getMessage());
//            e.printStackTrace();
//            e.printStackTrace();
//            throw new GunsException(BizExceptionEnum.APPLE_SFTP_UPLOAD_ERROR);
//        } finally {
//            if (sftpUtil != null){
//                sftpUtil.close();
//            }
//        }
//
//        log.info("上传完成 <<<<<<<<<<");
        return  remoteFile;
    }

    public static Map<String, Object> getXml(String filePath) throws IOException {
        InputStream is = new FileInputStream(new File(filePath));
        BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        StringBuilder sb = new StringBuilder();

        //读取HTTP请求内容
        String buffer = null;
        while ((buffer = br.readLine()) != null) {
            sb.append(buffer);
        }
        String xml = sb.toString().substring(sb.toString().indexOf("<!DOCTYPE"),sb.toString().indexOf("</plist>")+8);
        return XMLTOMap(xml);
    }


    public static  Map<String, Object> XMLTOMap(String xml) {

        JSONObject xmlJSONObj = null;
        try {
            xmlJSONObj = org.json.XML.toJSONObject(xml);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //设置缩进
        String jsonPrettyPrintString = null;
        try {
            jsonPrettyPrintString = xmlJSONObj.toString(4);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        Map<String,Object> result1 = JSON.parseObject(jsonPrettyPrintString,Map.class);
        System.out.println(result1);
        Map map1 =(Map) result1.get("plist");
        Map dict = (Map)map1.get("dict");
        JSONArray keyArray = (JSONArray) dict.get("key");
        JSONArray strArray = (JSONArray) dict.get("string");

        Map<String,Object> map = new HashMap<>();
        for (int i=0,keySize = keyArray.size(); i < keySize; i++){
            map.put(String.valueOf(keyArray.get(i)),strArray.get(i));
        }
        return map;
    }



}
